import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken ,MenuList,UserName} from '@/utils/auth'
import Layout from '@/views/layout/Layout'
//import { Notification } from 'element-ui'

var websocketApi= process.env.NODE_ENV === 'development' ? require('config/dev.env'):process.env.ENV_CONFIG==='sit'?require('config/sit.env'):require('config/prod.env')
websocketApi=eval(websocketApi.SOCKET_API);

const MenuListObj=new MenuList();
const UserNameObj=new UserName();
var websocket=null;
const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: UserNameObj.get(),
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },



    asyncRouter:[],
    qiNiuToken:"",
    menuList:MenuListObj.get(),//getMenuList()?JSON.parse(getMenuList()):[],

    loading:false,
    isDot:false
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ASYNCROUTER:(state,asyncRouter)=>{
      state.asyncRouter=asyncRouter
    },
    SET_QINIUTOKEN:(state,qiNiuToken)=>{
      state.qiNiuToken=qiNiuToken
    },
    SET_LOADING:(state,Loading)=>{
      state.loading=Loading
    },
    SET_ISDOT:(state,isDot)=>{
      state.isDot=isDot
    },
    SET_MENULIST:(state,menuList)=>{
      state.menuList=menuList
    },
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response.data
          setToken(data.token);            
          MenuListObj.add(data.menuList);
          UserNameObj.add(data.userName);
          commit('SET_ISDOT', data.notificationCount);
          commit('SET_MENULIST', data.menuList);
          commit('SET_NAME', data.userName);
          commit('SET_TOKEN', data.token);
          websocket  = new WebSocket(websocketApi+data.token);
          websocket.onopen = function onOpen() {
              websocket.send(JSON.stringify('连接成功'));
          };
          websocket.onmessage = function onMessage(evt) {
            var data = JSON.parse(evt.data);
            if(data.message){
              const h = VM.$createElement;
              VM.$notify({
                title: '消息提示',
                message: h('i', { style: 'color: teal'}, data.message),
                duration:30000
              });
              websocket.send(JSON.stringify('更新消息'));
            }
            commit('SET_ISDOT',data.notificationCount);
            
          }
          websocket.onclose = function onClose() {
            //console.log("断开1")
            //logout()
            return true
          };
          resolve()
          
        }).catch(error => {
          reject(error)
        })
      })
    },
    SetIsdot({ commit }, isDot){
       commit('SET_ISDOT', isDot);
    },
    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
          const data={
            role: ['admin'],
            token: 'admin',
            introduction: '我是超级管理员',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            name: 'Super Admin'
          };
          commit('SET_ROLES', data.role)
         /* commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)*/
          resolve(data)
        /*getUserInfo().then(response => { //state.token
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          };
          const data = response
          commit('SET_ROLES', data.role)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve(response)
        }).catch(error => {
          reject(error)
        })*/
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    Loading({ commit, state },bool){
       commit('SET_LOADING',bool )
    },
    SetQiNiuToken({ commit, state },token){
      commit('SET_QINIUTOKEN',token )
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    /*ChangeRole({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.role)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    }*/
  }
}

export default user;

export function closeUserSocket(){
  if(websocket){

      websocket.close();
  }else{
     return false
  }
};
export function sendUserSocket(){
  if(websocket){
    websocket.send(JSON.stringify('更新消息'));
    return true
  }else{
    return false
  }
};